package com.wsz.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 连接数据库工具类
 *
 * @author HHLJ
 * @date 2022/01/25
 */
public class JDBCUtils {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    /**
     * 注册JDBC驱动
     */
    static {
        try {
            //获取配置文件
            InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            //从配置文件中获取数据信息
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            try {
                //注册驱动
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("注册驱动失败");
        }
    }

    /**
     * 获取连接
     * @return Connection null连接失败 !null连接成功
     */
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 释放资源release()
     *
     * @param connection 连接
     * @param statement  执行命令
     * @param resultSet  结果集
     */
    public static void release(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement!= null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}






